<template>
  <div ref="content" style="height: calc(100vh - 180px)">
    <a-card :bordered="false">
      <split splitHeight="50%" leftWidth="200">
        <template slot="paneL">
          <!-- 部门树 -->
          <dept-tree
            ref="deptTree"
            :deptOptions="deptOptions"
            @setDataOptionInfo="setDataOptionInfo"
            :defalutExpandedKeys="expandedKeys"
            @select="clickDeptNode"
            :isKefu="isKefu"
          />
          <!-- :defalutExpandedKeys="expandedKeys" -->
        </template>
        <template slot="paneR">
          <!-- 条件搜索 -->
          <div class="table-page-search-wrapper">
            <a-form :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-row :gutter="10">
                <a-col :span="8">
                  <a-form-item label="姓名">
                    <a-input
                      v-model="queryParam.name"
                      placeholder="请输入姓名"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>

                <a-col :span="8">
                  <a-form-item label="手机号">
                    <a-input
                      v-model="queryParam.phonenumber"
                      placeholder="请输入手机号"
                      allow-clear
                      @keyup.enter.native="handleQuery"
                    />
                  </a-form-item>
                </a-col>

                <a-col>
                  <span
                    class="table-page-search-submitButtons"
                    style="float: right"
                  >
                    <a-button type="primary" @click="handleQuery"
                      ><a-icon type="search" />查询</a-button
                    >
                    <a-button style="margin-left: 8px" @click="resetQuery"
                      ><a-icon type="redo" />重置</a-button
                    >
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-divider />

          <a-row>
            <a-col :span="13">
              <div style="position: relative">
                <span
                  style="
                    position: absolute;
                    top: 0;
                    left: 0;
                    z-index: 1;
                    background: white;
                    padding: 0 12px;
                  "
                >
                  待选择
                </span>
                <advance-table
                  :columns="columns"
                  :data-source="list"
                  :title="tableTitle"
                  :loading="loading"
                  rowKey="id"
                  size="middle"
                  tableKey="system-user-SysUserIndex-table-changeuser"
                  @change="handleTableChange"
                  @refresh="getList"
                  :format-conditions="true"
                  :row-selection="{
                    selectedRowKeys: selectedRowKeys,
                    onSelect: onSelect,
                    onSelectAll: onSelectAll,
                    type: isCheckBox ? 'checkbox' : 'radio',
                  }"
                  :isShowColumns="false"
                  :isShowRefresh="false"
                  :showHeader="true"
                  :scroll="{ x: '100%', y: 'calc(90vh - 420px)' }"
                  :pagination="{
                    current: queryParam.pageNum,
                    pageSize: queryParam.pageSize,
                    total: total,
                    showSizeChanger: true,
                    showLessItems: true,
                    showQuickJumper: false,
                    showTotal: (total, range) =>
                      `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
                    onChange: changeSize,
                    onShowSizeChange: onShowSizeChange,
                  }"
                >
                  <span slot="status" slot-scope="{ record }">
                    <a-badge
                      :status="record.status == '0' ? 'processing' : 'error'"
                      :text="statusFormat(record)"
                    />
                  </span>
                  <span slot="customerType" slot-scope="{ record }">
                    <span
                      v-for="(item, i) in JSON.parse(record.customerType)"
                      :key="i"
                      >{{ customerTypeFormat(item) }},</span
                    >
                  </span>
                  <span slot="companyId" slot-scope="{ text }">
                    {{ companyFormat(companyList, text) }}
                  </span>

                  <span slot="name" slot-scope="{ text, record, index }">
                    <a @click="onClickRow(record, index)">
                      <a-avatar
                        :style="{ backgroundColor: getRandomColor(index) }"
                        style="color: #fff"
                      >
                        {{ getShowName(text) }}
                      </a-avatar>
                      {{ text }}
                    </a>
                  </span>
                  <span slot="createTime" slot-scope="text, record">
                    {{ parseTime(record.createTime) }}
                  </span>
                  <span slot="money" slot-scope="{ text }">
                    ¥&nbsp; {{ parseFloat(text ? text : 0).toFixed(2) }}
                  </span>

                  <span slot="busType" slot-scope="{ record }">
                    {{ busTypeFormat(record) }}
                  </span>
                </advance-table>
              </div>
            </a-col>
            <a-col :span="11">
              <div style="position: relative">
                <span
                  style="
                    position: absolute;
                    top: 0;
                    left: 0;
                    z-index: 1;
                    background: white;
                    padding: 0 12px;
                  "
                >
                  已选择
                </span>
                <advance-table
                  :columns="columns"
                  :data-source="selectedRows"
                  :title="tableTitle"
                  :loading="loading"
                  rowKey="id"
                  size="middle"
                  tableKey="system-user-SysUserIndex-table-show-changeuser"
                  :format-conditions="true"
                  :isShowColumns="false"
                  :isShowRefresh="false"
                  :scroll="{ x: '100%', y: 'calc(90vh - 420px)' }"
                  :pagination="{
                    current: queryParam.pageNum,
                    pageSize: queryParam.pageSize,
                    total: selectedRows.length,
                    showSizeChanger: true,
                    showLessItems: true,
                    showQuickJumper: false,
                    showTotal: (total, range) =>
                      `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
                    onChange: changeSize,
                    onShowSizeChange: onShowSizeChange,
                  }"
                >
                  <span slot="status" slot-scope="{ record }">
                    <a-badge
                      :status="record.status == '0' ? 'processing' : 'error'"
                      :text="statusFormat(record)"
                    />
                  </span>
                  <span slot="customerType" slot-scope="{ record }">
                    <span
                      v-for="(item, i) in JSON.parse(record.customerType)"
                      :key="i"
                      >{{ customerTypeFormat(item) }},</span
                    >
                  </span>
                  <span slot="companyId" slot-scope="{ text }">
                    {{ companyFormat(companyList, text) }}
                  </span>

                  <span slot="name" slot-scope="{ text, record, index }">
                    <a @click="onClickRow(record, index)">
                      <a-avatar
                        :style="{ backgroundColor: getRandomColor(index) }"
                        style="color: #fff"
                      >
                        {{ getShowName(text) }}
                      </a-avatar>
                      {{ text }}
                    </a>
                  </span>
                  <span slot="createTime" slot-scope="text, record">
                    {{ parseTime(record.createTime) }}
                  </span>
                  <span slot="money" slot-scope="{ text }">
                    ¥&nbsp; {{ parseFloat(text ? text : 0).toFixed(2) }}
                  </span>

                  <span slot="busType" slot-scope="{ record }">
                    {{ busTypeFormat(record) }}
                  </span>
                </advance-table>
              </div>
            </a-col>
          </a-row>
        </template>
      </split>
    </a-card>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  exportUser,
  importTemplate,
  findListUserBycompanyId,
} from "@/api/system/user";

import { listDeptTree } from "@/api/system/dept";
import DeptTree from "./DeptTree";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import Split from "@/components/pt/split/Index";
export default {
  name: "User",
  props: {
    isCheckBox: {
      type: Boolean,
    },
    isKefu: {
      type: Number,
      default: 0,
    },
    postIds: {
      type: Array,
    },
  },
  components: {
    AdvanceTable,
    Split,
    DeptTree,
  },
  data() {
    return {
      zyUserId: "",
      zyUserList: [],
      consultUserId: "",
      zyvisible: false,
      genjinuser: 0,
      confirmLoading: false,
      showAddModal: false,
      showEditModal: false,
      showResetPassword: false,
      list: [],
      colorList: ["#F38709", "#813AFD", "#00C4AA", "#4B7AEE"],
      tableTitle: "用户列表",
      selectedRowKeys: [],
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      userNames: [],
      expandedKeys: [],
      loading: false,
      total: 0,
      // 状态数据字典
      statusOptions: [],
      sexOptions: [],
      userTypeOptions: [],
      deptCheckedValue: {},
      // 部门树选项
      deptOptions: [],
      // 客户类型字典
      customerTypeOptions: [],
      // 公司信息
      companyList: [],
      // 业务类型
      busTypeOptions: [],
      // 日期范围
      dateRange: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      queryParam: {
        pageNum: 1,
        pageSize: 20,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      columns: [
        {
          title: "姓名",
          dataIndex: "name",
          width: "120px",
          scopedSlots: { customRender: "name" },
        },
        {
          title: "部门名称",
          dataIndex: "sysDept.deptName",
          // scopedSlots: { customRender: "companyId" },
          ellipsis: true,
          width: "100px",
        },

        {
          title: "电话",
          dataIndex: "phonenumber",
          align: "center",
        },
        // {
        //   title: "业务城市",
        //   dataIndex: "city",
        //   align: "center",
        //   ellipsis: true,
        // },
        // {
        //   title: "客户类型",
        //   dataIndex: "customerType",
        //   scopedSlots: { customRender: "customerType" },
        //   align: "center",
        //   width: 80,
        // },
        // {
        //   title: "日分配人数",
        //   dataIndex: "dayCount",
        //   align: "right",
        //   width: 90,
        // },
        // {
        //   title: "次费用",
        //   dataIndex: "money",
        //   align: "right",
        //   scopedSlots: { customRender: "money" },
        // },
        // {
        //   title: "用户类型",
        //   width: 90,
        //   scopedSlots: { customRender: "busType" },
        //   dataIndex: "busType",
        //   align: "center",
        // },
      ],
    };
  },
  filters: {},
  created() {
    this.getList();
    this.getTreeselect();
    this.getDicts("status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
    });
    this.getDicts("sys_user_type").then((response) => {
      this.userTypeOptions = response.data;
    });
    this.getDicts("customer_type").then((response) => {
      this.customerTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.busTypeOptions = response.data;
    });
    this.getCompanyInfos({}).then((res) => {
      this.companyList = res.data;
    });
  },
  computed: {},
  watch: {},
  methods: {
    findListUserBycompanyId() {
      findListUserBycompanyId().then((res) => {
        this.zyUserList = res.data;
      });
    },
    showModalzy() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 0;
    },
    showModalzyConsult() {
      this.findListUserBycompanyId();
      this.zyvisible = true;
      this.genjinuser = 1;
    },
    handleOk(e) {
      this.confirmLoading = true;
      setTimeout(() => {
        this.zyvisible = false;
        this.confirmLoading = false;
        const userIds = this.ids;
        if (userIds.length > 1) {
          this.$error({
            title: "错误提示！",
            content: "只能选择一条数据！",
          });
          return;
        }
      }, 2000);
    },
    handleCancel(e) {
      this.zyvisible = false;
    },
    importTemplate(expanded, record) {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      if (this.isKefu === 2) {
        listDeptTree("0", 3, 2).then((response) => {
          this.deptOptions = response.data;
          this.getExpandedKeys(this.deptOptions, 2);
        });
      } else {
        listDeptTree("0", 3).then((response) => {
          this.deptOptions = response.data;
          this.getExpandedKeys(this.deptOptions, 2);
        });
      }
    },
    getExpandedKeys(nodes, expandLevel) {
      if (expandLevel > 1) {
        // 最后一层不展开
        if (nodes != null) {
          nodes.forEach((node) => {
            this.expandedKeys.push(node.id);
            expandLevel = expandLevel - 1;
            return this.getExpandedKeys(node.children, expandLevel);
          });
        }
      }
    },
    // 客户类型字典翻译
    customerTypeFormat(customerType) {
      if (customerType) {
        return this.selectDictLabel(this.customerTypeOptions, customerType);
      } else {
        return "";
      }
    }, // 客户类型字典翻译
    busTypeFormat(row) {
      if (row.busType) {
        return this.selectDictLabel(this.busTypeOptions, row.busType);
      } else {
        return "";
      }
    },
    companyFormat(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].id === "" + value) {
          actions.push(datas[key].companyName);
          return true;
        }
      });
      return actions.join("");
    },
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.shareStatus);
    },
    userTypeFormat(row) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    /** 查询定时任务列表 */
    getList() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.loading = true;
      var params = this.addDateRange(this.queryParam, this.dateRange);
      // this.queryParam = this.isKefu;

      if (this.isKefu) {
        params.isKefu = this.isKefu;
      }
      if (this.postIds) {
        params.postIds = this.postIds;
      }
      listUser(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParam = {
        pageNum: 1,
        pageSize: 20,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      };
      this.handleQuery();
    },
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },

    onSelectAll(selected, selectedRows, changeRows) {
      // console.log("selected", selected);
      // console.log("selectedRows", selectedRows);
      // console.log("changeRows", changeRows);
      if (selected) {
        // 全选
        // 创建一个Map来去重
        const rowMap = new Map();

        // 添加selectedRows1
        this.selectedRows.forEach((row) => {
          rowMap.set(row.id, row);
        });

        // 添加selectedRows2（会覆盖重复项）
        selectedRows.forEach((row) => {
          rowMap.set(row.id, row);
        });

        // 转换回数组
        this.selectedRows = Array.from(rowMap.values());
        this.selectedRowKeys = this.selectedRows.map((item) => item.id);
      } else {
        // 获取当前页所有行的ID（如果是分页表格）
        const currentPageIds = this.list.map((item) => item.id);

        // 从已选中行中移除当前页的行
        this.selectedRows = this.selectedRows.filter(
          (row) => !currentPageIds.includes(row.id)
        );
        console.log("取消全选", this.selectedRows);
        this.selectedRowKeys = this.selectedRows.map((item) => item.id);
      }

      this.ids = this.selectedRows.map((item) => item.id);
      this.userNames = this.selectedRows.map((item) => item.name);
      this.$emit("getUser", this.selectedRows);
      this.single = this.selectedRowKeys.length !== 1;
      this.multiple = !this.selectedRowKeys.length;
    },
    onSelect(record, selected, selectedRows, nativeEvent) {
      console.log("record", record);
      console.log("selected", selected);
      console.log("selectedRows", selectedRows);
      console.log("nativeEvent", nativeEvent);
      if (selected) {
        if (!this.isCheckBox) {
          // 如果是单选模式，清空之前的选中项
          this.selectedRowKeys = [];
          this.selectedRows = [];
        }
        // 选中
        this.selectedRowKeys.push(record.id);
        this.selectedRows.push(record);
      } else {
        // 取消选中
        const index = this.selectedRowKeys.indexOf(record.id);
        if (index > -1) {
          this.selectedRowKeys.splice(index, 1);
          this.selectedRows.splice(index, 1);
        }
      }
      this.ids = this.selectedRows.map((item) => item.id);
      this.userNames = this.selectedRows.map((item) => item.name);
      this.$emit("getUser", this.selectedRows);
      this.single = this.selectedRowKeys.length !== 1;
      this.multiple = !this.selectedRowKeys.length;
    },

    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    clickDeptNode(node) {
      this.queryParam.deptId = node.$options.propsData.eventKey;
      this.deptCheckedValue.ids = node.$options.propsData.eventKey;
      this.tableTitle = node.$options.propsData.label;
      if (node.$options.propsData.dataRef.attributes.deptType === "dept") {
        this.deptCheckedValue = {
          ids: node.$options.propsData.eventKey,
          names: node.$options.propsData.label,
        };
      } else {
        this.deptCheckedValue = {};
      }
      this.getList();
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.sysUserAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.sysUserEditForm.handleUpdate(record, ids)
      );
    },
    handleResetPwd(record) {
      this.showResetPassword = true;
      this.$nextTick(() => this.$refs.resetPassword.handleResetPwd(record));
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const userIds = row.id || this.ids;
      const userNames = row.name || this.userNames;
      this.$confirm({
        title: "确认删除所选中数据?",
        content: "当前选中编号为" + userNames + "的数据",
        onOk() {
          return delUser(userIds).then(() => {
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportUser(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
    getRandomColor(index) {
      // const randomValue = Math.round(Math.random() * 3)
      return this.colorList[index % 4];
    },
    getShowName(name) {
      if (name.length > 2) {
        name = name.substring(name.length - 2);
      }
      return name;
    },
    onClickRow(record, index) {
      this.handleUpdate(record, "");
    },
    setDataOptionInfo(treeDataOption) {
      this.deptOptions = treeDataOption;
    },
    handleTableChange(pagination, filters, sorter) {
      if (
        sorter.field !== undefined &&
        sorter.field !== null &&
        sorter.field !== ""
      ) {
        this.queryParam.orderByColumn = "t." + sorter.field;
        this.queryParam.isAsc = sorter.order;
      }
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.ant-divider-horizontal {
  margin: 0;
  background: rgb(235, 237, 240);
}
.demo-split {
  height: 200px;
}
.demo-split-pane {
  padding: 10px;
}
.ant-avatar {
  font-size: 12px;
  border-radius: 4px;
  vertical-align: middle;
  margin-right: 8px;
}

/deep/.ant-table-body {
  min-height: 60vh;
}
/deep/.ant-table-placeholder {
  // 将暂无数据提示隐藏，否则没有数据时将表格高度制定导致暂无数据挤到最底下
  display: none;
}
</style>
